package types

import (
	"encoding/json"
	"net/http"

	"cashway.com/cis/assistant/model"
)

type HttpHandleFunc = func(resp http.ResponseWriter, req *http.Request)
type HandleFunc[T any] func(resp *ResponseWriter, req *Request[T])
type MiddlewareFunc[T any] func(HandleFunc[T]) HandleFunc[T]

type JsonObj interface{}

type Request[T any] struct {
	http.Request
	ReqBody T
	IsAsync bool
}

type ResponseWriter struct {
	http.ResponseWriter
	RespBody JsonObj
}

func (resp *ResponseWriter) RespJson(body JsonObj) {
	resp.RespBody = body
	bytes, err := json.Marshal(body)
	if err != nil {
		resp.WriteHeader(http.StatusInternalServerError)
		return
	}
	resp.RespBody = body
	resp.Header().Add("Content-Type", "application/json; charset=utf-8")
	resp.Write(bytes)
}

func (resp *ResponseWriter) RespJsonInternalServerError() {
	resp.WriteHeader(http.StatusInternalServerError)
	resp.RespJson(&model.JsonResp{
		Code: http.StatusInternalServerError,
		Msg:  "server internal error",
	})
}

func (resp *ResponseWriter) RespJsonCommonFailedMsg(args ...string) {
	argLen := len(args)
	var msg = "failed"
	if argLen > 0 {
		msg = args[0]
	}

	resp.RespJson(&model.JsonResp{
		Code: 1,
		Msg:  msg,
		Data: nil,
	})
}

func (resp *ResponseWriter) RespJsonCommonSuccess(args ...JsonObj) {
	argLen := len(args)
	var body JsonObj
	if argLen == 1 {
		body = args[0]
	} else if argLen > 1 {
		body = args
	}
	resp.RespJson(&model.JsonResp{
		Code: 0,
		Msg:  "ok",
		Data: body,
	})
}
